<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------

namespace app\Manage\controller;

use app\common\controller\Manage;
use app\common\model\BookApply as BookApplysModel;
use app\common\model\BookApplyDetail as BookApplyDetailsModel;
use app\common\model\BookBatchDraw as BookBatchDrawsModel;
use app\common\model\BookExtraDraw as BookExtraDrawsModel;
use app\common\model\BookSupplyDraw as BookSupplyDrawModel;
use app\common\model\BookDraw as BookDrawModel;
use app\common\model\ViewGetDepts as ViewGetDeptsModel;
use app\common\model\ViewGetSpecicalties as ViewGetSpecicaltiesModel;
use app\common\model\ViewGetYears as ViewGetYearsModel;
use app\common\model\ViewGetSeasons as ViewGetSeasonsModel;
use app\common\model\ViewGetDirs as ViewGetDirsModel;
use app\common\model\SupplyBookInfo as SupplyBookInfoModel;
use app\common\model\BookSupplyDrawDetail as BookSupplyDrawDetailModel;
use app\common\model\BookPlan as BookPlanModel;
use app\common\model\BookInfo as BookInfoModel;
use app\common\model\Config as ConfigsModel;
use app\common\model\Manage as ManageModel;
use app\common\model\Common as UModel;
use app\common\model\StudentType as StudentTypeModel;
use app\common\model\StudentTypeParams as StudentTypeParamsModel;
use app\common\model\StudentTypeRel as StudentTypeRelModel;
use app\common\model\StudentTypeBookRel as StudentTypeBookRelModel;
use app\common\model\BookExtraDraw as BookExtraDrawModel;
use app\common\model\SubCenter as SubCenterModel;
use app\common\model\ViewGetSubCenter as ViewGetSubCenterModel;

use think\facade\Request;
use think\facade\Log;

class BookDraw extends Manage
{
    // 教材批量发放
    public function bookdrawindex()
    {    
        if(Request::isAjax())
        {
            $bookapplyModel = new BookApplysModel();
            return $bookapplyModel->tableData(input('param.'));
        }
        
        //获取年度列表
        $viewGetYearsModel = new ViewGetYearsModel();
        $yearList = $viewGetYearsModel->select();
        $this->assign('yearList', $yearList);

        //获取季度列表
        $viewGetSeasonsModel = new ViewGetSeasonsModel();
        $seasonList = $viewGetSeasonsModel->select();
        $this->assign('seasonList', $seasonList);

        //获取专业列表
        $viewGetDeptsModel = new ViewGetDeptsModel();
        $deptList = $viewGetDeptsModel->select();
        $this->assign('deptList', $deptList);
        
        //获取方向列表
        $ViewGetDirsModel = new ViewGetDirsModel();
        $dirList = $ViewGetDirsModel->select();
        $this->assign('dirList', $dirList);

        // 默认值
        $ConfigsModel = new ConfigsModel();
        $year = $ConfigsModel->getYear();
        $season = $ConfigsModel->getSeason();
        $this->assign('year', $year);
        $this->assign('season', $season);
        $this->assign('userId', session('manage.id'));
        return $this->fetch("/book_batch_draw/index");
    }


    // 教材批量发放：发放
    public function changestatus()
    {
        $bookapplyModel = new BookApplysModel();
        return $bookapplyModel->changeStatus(input('param.'));
    }
 
    // 教材批量发放：查看明细
    public function bookdrawdetail()
    {       
        if(Request::isAjax())
        {
            # 会自行解析url中的参数
            $bookapplydetailModel = new BookApplyDetailsModel();
            return $bookapplydetailModel->tableData(input('param.'));
        } 

        // 往前台页面传参
        if(input('param.')['applyid']) {
            $applyid = input('param.')['applyid'];
            $this->assign('applyid', $applyid);

            // 根据id获取发放信息
            $bookapplyModel = new BookApplysModel();
            $post = ['id' => $applyid];
            $res = $bookapplyModel->tableData($post);

            // 填充明细页面上方显示的只读文本框
            if($res["count"]) {
                $bookapplyInfo = $res["data"];
                $this->assign('dep', $bookapplyInfo[0]['dep']);
                $this->assign('specialty', $bookapplyInfo[0]['specialty']);
                $this->assign('class', $bookapplyInfo[0]['class']);
                $this->assign('dir', $bookapplyInfo[0]['dir']);
                $this->assign('teacher', $bookapplyInfo[0]['teacher']);
            }
        }
        return $this->fetch("/book_batch_draw/detail");
    }

    // 教材批量发放：删除计划
    public function bookdrawdel()
    {
        $applyid = input('param.')['applyid'];
        // 判断该计划中是否有学生已经领过书了，已经领取不能删除
        $bookapplyModel = new BookApplysModel();
        $bookapplydetailModel = new BookApplyDetailsModel();
        $status = $bookapplydetailModel->getDrawStatus($applyid);
        if($status) {
            $return_data = array(
                'status' => false,
                'msg'    => '该申请中已经有学生签收了教材，无法删除！',
                'data'   => []
            );
            return $return_data;
        }

        // 这里直接调用SQL查询数据
        $model = new UModel();
        $model->query("call bookDrawDel('".$applyid."');");
    
        $return_data = array(
            'status' => true,
            'msg'    => '删除成功',
            'data'   => []
        );

        return $return_data;
    }

    // 教材批量发放：删除学生
    public function bookdrawdelstudent()
    {       
        $id = input('param.')['id'];
        // 判断该计划中是否有学生已经领过书了，已经领取不能删除
        $bookapplyModel = new BookApplysModel();
        $bookapplydetailModel = new BookApplyDetailsModel();
        $detailInfo = $bookapplydetailModel->where(['id'=>$id])->find();
        if($detailInfo && $detailInfo['is_qs'] == 1) {
            $return_data = array(
                'status' => false,
                'msg'    => '该学生签收了教材，无法删除！',
                'data'   => []
            );
            return $return_data;
        }

        $model = new UModel();
        $model->query("call bookDrawDelStudent('".$id."');");
         
        $return_data = array(
            'status' => true,
            'msg'    => '删除成功',
            'data'   => []
        );
        
        return $return_data;
    }

    // 教材预发放
    public function bookpredrawindex()
    {       
        if(Request::isAjax())
        {
            $bookbatchdrawModel = new BookBatchDrawsModel();
            return $bookbatchdrawModel->tableData(input('param.'));
        }

        //获取年度列表
        $viewGetYearsModel = new ViewGetYearsModel();
        $yearList = $viewGetYearsModel->select();
        $this->assign('yearList', $yearList);

        //获取季度列表
        $viewGetSeasonsModel = new ViewGetSeasonsModel();
        $seasonList = $viewGetSeasonsModel->select();
        $this->assign('seasonList', $seasonList);

        //获取部门列表
        $viewGetDeptsModel = new ViewGetDeptsModel();
        $deptList = $viewGetDeptsModel->select();
        $this->assign('deptList', $deptList);
        
        //获取方向列表
        $ViewGetDirsModel = new ViewGetDirsModel();
        $dirList = $ViewGetDirsModel->select();
        $this->assign('dirList', $dirList);

        // 默认值
        $ConfigsModel = new ConfigsModel();
        $year = $ConfigsModel->getYear();
        $season = $ConfigsModel->getSeason();
        $this->assign('year', $year);
        $this->assign('season', $season);
        $this->assign('userId', session('manage.id'));
        return $this->fetch("/book_pre_draw/index");
    }

    
    // 教材预发放：预发放
    public function predrawsave()
    {
        $this->view->engine->layout(false);
        $bookbatchdrawModel = new BookBatchDrawsModel();
        if(Request::isPost())
        {
            return $bookbatchdrawModel->predrawSave(input('param.'));
        }
        
        //获取年度列表
        $viewGetYearsModel = new ViewGetYearsModel();
        $yearList = $viewGetYearsModel->select();
        $this->assign('yearList', $yearList);

        //获取季度列表
        $viewGetSeasonsModel = new ViewGetSeasonsModel();
        $seasonList = $viewGetSeasonsModel->select();
        $this->assign('seasonList', $seasonList);

        //获取部门列表
        $viewGetDeptsModel = new ViewGetDeptsModel();
        $deptList = $viewGetDeptsModel->select();
        $this->assign('deptList', $deptList);
        
        //获取方向列表
        $ViewGetDirsModel = new ViewGetDirsModel();
        $dirList = $ViewGetDirsModel->select();
        $this->assign('dirList', $dirList);

        // 默认值
        $ConfigsModel = new ConfigsModel();
        $year = $ConfigsModel->getYear();
        $season = $ConfigsModel->getSeason();
        $this->assign('year', $year);
        $this->assign('season', $season);
        return $this->fetch('/book_pre_draw/draw');
    }


    // 教材预发放：修改
    public function bookpredrawedit()
    {       
        $this->view->engine->layout(false);
        $bookbatchdrawModel = new BookBatchDrawsModel();
        if(Request::isPost())
        {
            return $bookbatchdrawModel->saveData(input('param.'));
        }
        $data = $bookbatchdrawModel->getinfobyid(input('param.'));
        if (!$data) {
            return error_code(10002);
        }
        return $this->fetch('/book_pre_draw/edit',['data' => $data]);
    }


    // 批量打印（预发放）
    public function drawprintindex()
    {
        if(Request::isAjax())
        {
            $bookbatchdrawModel = new BookBatchDrawsModel();
            return $bookbatchdrawModel->tableData(input('param.'));
        }
        
        //获取年度列表
        $viewGetYearsModel = new ViewGetYearsModel();
        $yearList = $viewGetYearsModel->select();
        $this->assign('yearList', $yearList);

        //获取季度列表
        $viewGetSeasonsModel = new ViewGetSeasonsModel();
        $seasonList = $viewGetSeasonsModel->select();
        $this->assign('seasonList', $seasonList);

        //获取部门列表
        $viewGetDeptsModel = new ViewGetDeptsModel();
        $deptList = $viewGetDeptsModel->select();
        $this->assign('deptList', $deptList);
        
        //获取方向列表
        $ViewGetDirsModel = new ViewGetDirsModel();
        $dirList = $ViewGetDirsModel->select();
        $this->assign('dirList', $dirList);
        
        // 默认值
        $ConfigsModel = new ConfigsModel();
        $year = $ConfigsModel->getYear();
        $season = $ConfigsModel->getSeason();
        $this->assign('year', $year);
        $this->assign('season', $season);
        return $this->fetch("/book_draw_print/index");
    }

    // 教材预发放：重置打印状态 1->0
    public function bookpreresetprintstatus()
    {
        $bookbatchdrawModel = new BookBatchDrawsModel();
        return $bookbatchdrawModel->bookpreresetprintstatus(input('param.'));
    }

    // 教材预发放：打印状态改变 0->1
    public function bookpreprintstatus()
    {
        $bookbatchdrawModel = new BookBatchDrawsModel();
        return $bookbatchdrawModel->bookpreprintstatus(input('param.'));
    }
     
    // 教材补发
    public function booksupplydrawindex()
    {       
        if(Request::isAjax())
        {
            $bookSupplyDrawModel = new BookSupplyDrawModel();
            return $bookSupplyDrawModel->tableData(input('param.'));
        }

        //获取年度列表
        $viewGetYearsModel = new ViewGetYearsModel();
        $yearList = $viewGetYearsModel->select();
        $this->assign('yearList', $yearList);

        //获取季度列表
        $viewGetSeasonsModel = new ViewGetSeasonsModel();
        $seasonList = $viewGetSeasonsModel->select();
        $this->assign('seasonList', $seasonList);

        //获取部门列表
        $viewGetDeptsModel = new ViewGetDeptsModel();
        $deptList = $viewGetDeptsModel->select();
        $this->assign('deptList', $deptList);
        
        //获取方向列表
        $ViewGetDirsModel = new ViewGetDirsModel();
        $dirList = $ViewGetDirsModel->select();
        $this->assign('dirList', $dirList);

        // 默认值
        $ConfigsModel = new ConfigsModel();
        $year = $ConfigsModel->getYear();
        $season = $ConfigsModel->getSeason();
        $this->assign('year', $year);
        $this->assign('season', $season);
        $this->assign('userId', session('manage.id'));
        return $this->fetch("/book_supply_draw/index");
    }

    // 教材补发：增加图书
    public function supplyAddBook()
    {
        $this->view->engine->layout(false);
        $supplyBookInfoModel = new SupplyBookInfoModel();
        if(Request::isPost())
        {
            $data['plan_operid'] = session('manage.id');
            $data['plan_book_id'] = input('book_id', '');
            $data['plan_price'] = input('plan_price', '');
            $data['book_disc'] = input('book_disc', '');
            $data['plan_book_num'] = input('plan_book_num', '');
            return $supplyBookInfoModel->add($data);
        }
        
        $bookInfoModel = new BookInfoModel();
        $bookList = $bookInfoModel->getBookList();
        $this->assign('bookList', $bookList);

        return $this->fetch('/book_supply_draw/add_book');
    }

    // 教材补发：删除图书
    public function supplyDelBook()
    {
        $result = ['status' => true,'msg' => '删除成功','data'=>''];
        // 不需要做任何逻辑判定直接删除
        $supplyBookInfoModel = new SupplyBookInfoModel();
        $supplyBookInfoModel->where(['id' => input('id', '')])->delete();

        return $result;
    }
    
    // 教材补发：补发
    public function supplydrawsave()
    {
        $bookSupplyDrawModel = new BookSupplyDrawModel();
        if(Request::isPost())
        {
            return $bookSupplyDrawModel->supplydrawsave(input('param.'));
        }
        
        //获取年度列表
        $viewGetYearsModel = new ViewGetYearsModel();
        $yearList = $viewGetYearsModel->select();
        $this->assign('yearList', $yearList);

        //获取季度列表
        $viewGetSeasonsModel = new ViewGetSeasonsModel();
        $seasonList = $viewGetSeasonsModel->select();
        $this->assign('seasonList', $seasonList);

        //获取部门列表
        $viewGetDeptsModel = new ViewGetDeptsModel();
        $deptList = $viewGetDeptsModel->select();
        $this->assign('deptList', $deptList);
        
        //获取年级列表
        $bookPlanModel = new BookPlanModel();
        $gradeList = $bookPlanModel->getGradeList();
        $this->assign('gradeList', $gradeList);
        
        //获取层次列表
        $bookPlanModel = new BookPlanModel();
        $degreeList = $bookPlanModel->getDegreeList();
        $this->assign('degreeList', $degreeList);

        //获取方向列表
        $ViewGetDirsModel = new ViewGetDirsModel();
        $dirList = $ViewGetDirsModel->select();
        $this->assign('dirList', $dirList);

        // 默认值
        $ConfigsModel = new ConfigsModel();
        $year = $ConfigsModel->getYear();
        $season = $ConfigsModel->getSeason();
        $this->assign('year', $year);
        $this->assign('season', $season);
        return $this->fetch('/book_supply_draw/draw');
    }

    // 教材补发：教材列表
    public function supplyBookList()
    {
        // 获取当前账号
        $supplyBookInfoModel = new SupplyBookInfoModel();
        $where['operid'] = session('manage.id');
        $where['limit'] = input('limit');
        return $supplyBookInfoModel->tableData($where);
    }
   
    // 教材补发：重置打印状态 1->0
    public function booksupplyresetprintstatus()
    {
        $bookSupplyDrawModel = new BookSupplyDrawModel();
        return $bookSupplyDrawModel->booksupplyresetprintstatus(input('param.'));
    }

    // 教材补发：打印状态改变 0->1
    public function booksupplyprintstatus()
    {
        $bookSupplyDrawModel = new BookSupplyDrawModel();
        return $bookSupplyDrawModel->booksupplyprintstatus(input('param.'));
    }

    // 教材补发：查看明细
    public function booksupplydrawdetail()
    {       
        if(Request::isAjax())
        {
            # 会自行解析url中的参数
            $bookSupplyDrawDetailModel = new BookSupplyDrawDetailModel();
            return $bookSupplyDrawDetailModel->tableData(input('param.'));
        } 

        // 往前台页面传参
        if(input('param.')['supplyid']) {
            $supplyid = input('param.')['supplyid'];
            $this->assign('supplyid', $supplyid);
        }
        return $this->fetch("/book_supply_draw/detail");
    }

    // 教材补发：删除计划
    public function booksupplydrawdel()
    {
        $supplyid = input('param.')['supplyid'];
        
        // 判断是否已经退书
        $bookSupplyDrawModel = new BookSupplyDrawModel();
        $bookInfo = $bookSupplyDrawModel->field('g.book_name')
            ->alias('a')
            ->join('zl_book_supply_draw_detail b', 'a.id = b.supply_id')
            ->join('zl_book_draw c', 'a.class_id = c.draw_class_id')
            ->join('zl_book_plan d', "b.plan_id = d.id")
            ->join('zl_book_return e', 'a.year = e.draw_year and a.season = e.draw_season and c.xh = e.xh')
            ->join('zl_book_return_detail f', 'e.id = f.return_id and d.plan_book_id = f.book_id')
            ->join('zl_book_info g', 'd.plan_book_id = g.id')
            ->where(['a.id'=>$supplyid])
            ->find();

        if($bookInfo){
            $return_data = array(
                'status' => false,
                'msg'    => '删除失败，'.$bookInfo['book_name'].'已退书',
                'data'   => []
            );
            return $return_data;
        }

        // 判断是否已经调整
        $bookSupplyDrawModel = new BookSupplyDrawModel();
        $bookInfo = $bookSupplyDrawModel->field('g.book_name')
            ->alias('a')
            ->join('zl_book_supply_draw_detail b', 'a.id = b.supply_id')
            ->join('zl_book_draw c', 'a.class_id = c.draw_class_id')
            ->join('zl_book_plan d', "b.plan_id = d.id")
            ->join('zl_book_adjust e', 'a.year = e.year and a.season = e.season and c.xh = e.xh and d.plan_book_id = e.book_id')
            ->join('zl_book_info g', 'd.plan_book_id = g.id')
            ->where(['a.id'=>$supplyid])
            ->find();

        if($bookInfo){
            $return_data = array(
                'status' => false,
                'msg'    => '删除失败，'.$bookInfo['book_name'].'已调整',
                'data'   => []
            );
            return $return_data;
        }

        // 这里直接调用SQL查询数据
        $model = new UModel();
        $model->query("call bookSupplyDrawDel('".$supplyid."');");
    
        $return_data = array(
            'status' => true,
            'msg'    => '删除成功',
            'data'   => []
        );

        return $return_data;
    }

    // 教材补发：删除教材
    public function booksupplydelbook()
    {       
        $supply_id = input('param.')['supply_id'];
        $plan_id = input('param.')['plan_id'];

        // 判断是否已经退书
        $bookSupplyDrawModel = new BookSupplyDrawModel();
        $bookInfo = $bookSupplyDrawModel->field('g.book_name')
            ->alias('a')
            ->join('zl_book_supply_draw_detail b', 'a.id = b.supply_id')
            ->join('zl_book_draw c', 'a.class_id = c.draw_class_id')
            ->join('zl_book_plan d', "b.plan_id = d.id")
            ->join('zl_book_return e', 'a.year = e.draw_year and a.season = e.draw_season and c.xh = e.xh')
            ->join('zl_book_return_detail f', 'e.id = f.return_id and d.plan_book_id = f.book_id')
            ->join('zl_book_info g', 'd.plan_book_id = g.id')
            ->where(['a.id'=>$supply_id, 'b.plan_id'=>$plan_id])
            ->find();

        if($bookInfo){
            $return_data = array(
                'status' => false,
                'msg'    => '删除失败，'.$bookInfo['book_name'].'已退书',
                'data'   => []
            );
            return $return_data;
        }

        // 判断是否已经调整
        $bookSupplyDrawModel = new BookSupplyDrawModel();
        $bookInfo = $bookSupplyDrawModel->field('g.book_name')
            ->alias('a')
            ->join('zl_book_supply_draw_detail b', 'a.id = b.supply_id')
            ->join('zl_book_draw c', 'a.class_id = c.draw_class_id')
            ->join('zl_book_plan d', "b.plan_id = d.id")
            ->join('zl_book_adjust e', 'a.year = e.year and a.season = e.season and c.xh = e.xh and d.plan_book_id = e.book_id')
            ->join('zl_book_info g', 'd.plan_book_id = g.id')
            ->where(['a.id'=>$supply_id, 'b.plan_id'=>$plan_id])
            ->find();

        if($bookInfo){
            $return_data = array(
                'status' => false,
                'msg'    => '删除失败，'.$bookInfo['book_name'].'已调整',
                'data'   => []
            );
            return $return_data;
        }

        $model = new UModel();
        $model->query("call bookSupplyDelBook('".$supply_id."', '".$plan_id."');");
         
        $return_data = array(
            'status' => true,
            'msg'    => '删除成功',
            'data'   => []
        );
        
        return $return_data;
    }

    // 教材签收明细：查看
    public function bookdrawdetailindex()
    {       
        if(Request::isAjax())
        {
            $year = input('year', '');
            $season = input('season', '');
            $dep_id = input('dep_id', '');
            $specialty_id = input('specialty_id', '');
            $class_id = input('class_id', '');
            $dir = input('dir', '');
            $xh = input('xh', '');
            $xm = urldecode(input('xm', ''));
            $teacherName = urldecode(input('teacherName', ''));
            $limit = input('limit', 0); 
            $page = input('page', 0);
            $index = ($page - 1) * $limit;
            
            // 这里直接调用SQL查询数据
            $model = new UModel();
            $list = $model->query("call getBookDrawDetail('".$year."','".$season."','".$dep_id."','".$specialty_id."','".$class_id."','".$dir."','".$xh."','".$xm."','".$teacherName."',".$index.",".$limit.");");
    
            if(count($list) == 0){
                $re['code'] = 0;
                $re['msg'] = '';
                $re['count'] = 0;
                $re['data'] = [];
                return $re;
            }

            $re['code'] = 0;
            $re['msg'] = '';
            $re['count'] = count($list[1]);
            $re['data'] = $list[0];
            return $re;
        }

        // 如果是管理员则查询所有部门，否则查询用户所属部门
        $viewGetDeptsModel = new ViewGetDeptsModel();
        $manageModel = new manageModel();
        //if(session('manage')['id'] == $manageModel::TYPE_SUPER_ID){
            // 获取部门列表
            $dep_nameList = $viewGetDeptsModel->select();
            $this->assign('depList', $dep_nameList);
            $this->assign('bmdm', '');

        //获取年度列表
        $viewGetYearsModel = new ViewGetYearsModel();
        $yearList = $viewGetYearsModel->select();
        $this->assign('yearList', $yearList);

        //获取季度列表
        $viewGetSeasonsModel = new ViewGetSeasonsModel();
        $seasonList = $viewGetSeasonsModel->select();
        $this->assign('seasonList', $seasonList);

        // 默认值
        $ConfigsModel = new ConfigsModel();
        $year = $ConfigsModel->getYear();
        $season = $ConfigsModel->getSeason();
        $this->assign('curr_year', $year);
        $this->assign('curr_season', $season);
        // } else {
        //     $depList = [];
        //     $mgrInfo = $manageModel->where(['id' => session('manage')['id']])->find();
        //     if($mgrInfo) {
        //         $bmdm = $mgrInfo['deptId'];
        //         $bmmc = $viewGetDeptsModel->where(['bmdm' => $bmdm])->find()['bmmc'];
        //         $depList[] = ['bmdm'=> $bmdm, 'bmmc' => $bmmc];
        //         $this->assign('depList', $depList);
        //         $this->assign('bmdm', $bmdm);
        //     }
        // }

        return $this->fetch("/book_draw_detail/index");
    }

    //教材签收明细：替换
    public function studentreplace()
    {
        $id = input('param.')['id'];
        $this->view->engine->layout(false);
        $bookDrawModel = new BookDrawModel();
        if(Request::isPost())
        {
            $yxh = input('param.')['yxh'];
            $xxh = input('param.')['xxh'];
            $classid = input('param.')['classid'];

            // 这里直接调用SQL查询数据
            $model = new UModel();
            $model->query("call changeStudent('".$yxh."','".$xxh."','".$classid."');");
         
            $return_data = array(
                'status' => true,
                'msg'    => '替换成功',
                'data'   => []
            );

            return $return_data;
        }

        $data = $bookDrawModel->field('a.xh,a.draw_class_id,b.mobile')
            ->alias('a')
            ->join('zl_user b', 'a.draw_mgrid = b.id')
            ->where(['a.id'=>$id])->find();
        if (!$data) {
            return error_code(10002);
        }
        $yxh = $data['xh'];
        $class_id = $data['draw_class_id'];
        $mobile = $data['mobile'];
        // 这里直接调用SQL查询数据
        $model = new UModel();
        $list = $model->query("call programReplaceDetail('".$class_id."','".$mobile."');");
        if(count($list) == 0){
            $return_data = array(
                'status' => false,
                'msg'    => '当前年度季度班级下无未签收人员信息，无法进行替换操作，请确认！！！',
                'data'   => []
            );
            return $return_data;
        };
        $this->assign('replaceList', $list[0]);

        return $this->fetch('/book_draw_detail/studentReplace', ['id' => $id, 'yxh' => $yxh, 'classid' => $class_id]);
    }

    // 教材签收明细：删除
    public function bookdrawdetaildel()
    {       
        $id = input('param.')['id'];
        
        // 判断是否已经退书
        $bookDrawModel = new BookDrawModel();
        $bookInfo = $bookDrawModel->field('e.book_name')
            ->alias('a')
            ->join('zl_book_plan b', 'a.draw_class_id = b.plan_code')
            ->join('zl_book_return c', 'a.draw_year = c.draw_year and a.draw_season = c.draw_season and a.xh = c.xh')
            ->join('zl_book_return_detail d', "c.id = d.return_id and b.plan_book_id = d.book_id and d.type = 'plan'")
            ->join('zl_book_info e', 'b.plan_book_id = e.id')
            ->where(['a.id'=>$id])
            ->find();

        if($bookInfo){
            $return_data = array(
                'status' => false,
                'msg'    => '删除失败，'.$bookInfo['book_name'].'已退书',
                'data'   => []
            );
            return $return_data;
        }

        $bookDrawModel = new BookDrawModel();
        $bookInfo = $bookDrawModel->field('e.book_name')
            ->alias('a')
            ->join('zl_book_plan b', 'a.draw_class_id = b.plan_code')
            ->join('zl_book_adjust c', 'a.draw_year = c.year and a.draw_season = c.season and a.xh = c.xh and b.plan_book_id = c.book_id')
            ->join('zl_book_info e', 'b.plan_book_id = e.id')
            ->where(['a.id'=>$id])
            ->find();
 
        if($bookInfo){
            $return_data = array(
                'status' => false,
                'msg'    => '删除失败，'.$bookInfo['book_name'].'已调整',
                'data'   => []
            );
            return $return_data;
        }

        // 这里直接调用SQL查询数据
        $model = new UModel();
        $model->query("call bookDrawDetailDel('".$id."');");
         
        $return_data = array(
            'status' => true,
            'msg'    => '删除成功',
            'data'   => []
        );

        return $return_data;
    }
    
    // 非计划发放
    public function bookextradrawindex()
    {       
        if(Request::isAjax())
        {
            $bookExtraDrawsModel = new BookExtraDrawsModel();
            return $bookExtraDrawsModel->tableData(input('param.'));
        }

        //获取年度列表
        $viewGetYearsModel = new ViewGetYearsModel();
        $yearList = $viewGetYearsModel->select();
        $this->assign('yearList', $yearList);

        //获取季度列表
        $viewGetSeasonsModel = new ViewGetSeasonsModel();
        $seasonList = $viewGetSeasonsModel->select();
        $this->assign('seasonList', $seasonList);

        //获取部门列表
        $viewGetDeptsModel = new ViewGetDeptsModel();
        $deptList = $viewGetDeptsModel->select();
        $this->assign('deptList', $deptList);
        
        // 默认值
        $ConfigsModel = new ConfigsModel();
        $year = $ConfigsModel->getYear();
        $season = $ConfigsModel->getSeason();
        $this->assign('year', $year);
        $this->assign('season', $season);
        $this->assign('userId', session('manage.id'));
        return $this->fetch("/book_extra_draw/index");
    }
   
    // 非计划发放：教材明细
    public function bookextradrawbookdetail()
    { 
        $this->view->engine->layout(false);
        return $this->fetch("/book_extra_draw/bookdetail", ['id' => input('id')]);
    }

    // 非计划发放：教材明细
    public function getBookExtraDrawBookDetailList()
    {  
        $bookExtraDrawsModel = new BookExtraDrawsModel();
        return $bookExtraDrawsModel->getBookDetail(input('param.')); 
    }
 
    /**
     * 非计划发放：获取教材信息
     * @return array|mixed
     */
    public function getBookInfoByExtraDrawId()
    {
        $id  = input('param.id', '');     // 搜索关键字

        $bookPlanModel = new BookPlanModel();
        $list = $bookPlanModel->query("call getBookInfoByExtraDrawId('".$id."');");
        
        $result = [
            'status' => true,
            'data'   => $list[0],
            'msg'    => '查询成功'
        ];

        return $result;
    }

    // 非计划发放：学生明细
    public function bookextradrawstudentdetail()
    { 
        $id = input('param.')['id'];
        
        $this->view->engine->layout(false);
        
        $this->assign('id', $id);
        return $this->fetch("/book_extra_draw/studentdetail", ['id' => input('id')]);
    }

    // 非计划发放：学生明细
    public function getBookExtraDrawStudentDetailList()
    {  
        $bookExtraDrawsModel = new BookExtraDrawsModel();
        return $bookExtraDrawsModel->getStudentDetail(input('param.')); 
    }

    // 非计划发放：学生明细删除
    public function bookextradrawbookdetaildel()
    { 
        $extraId = input('param.')['extraId'];
        $detail_id = input('param.')['id'];

        // 判断是否已经退书
        $bookExtraDrawModel = new BookExtraDrawModel();
        $bookInfo = $bookExtraDrawModel->field('f.book_name, g.xm')
            ->alias('a')
            ->join('zl_book_extra_draw_detail b', 'a.id = b.draw_id')
            ->join('zl_student_type_book_rel c', 'a.year = c.plan_year and a.season = c.plan_season and a.type_id= c.type_id and a.param_id = c.param_id')
            ->join('zl_book_return d', "a.year = d.draw_year and a.season = d.draw_season and b.xh = d.xh")
            ->join('zl_book_return_detail e', 'd.id = e.return_id and c.book_id = e.book_id')
            ->join('zl_book_info f', 'c.book_id = f.id')
            ->join('zl_student_info g', 'b.xh = g.xh')
            ->where(['a.id'=>$extraId, 'b.id'=>$detail_id])
            ->find();

        if($bookInfo){
            $return_data = array(
                'status' => false,
                'msg'    => '删除失败，'.$bookInfo['xm'].'-'.$bookInfo['book_name'].'已退书',
                'data'   => []
            );
            return $return_data;
        }

        // 判断是否已经调整
        $bookExtraDrawModel = new BookExtraDrawModel();
        $bookInfo = $bookExtraDrawModel->field('f.book_name, g.xm')
            ->alias('a')
            ->join('zl_book_extra_draw_detail b', 'a.id = b.draw_id')
            ->join('zl_student_type_book_rel c', 'a.year = c.plan_year and a.season = c.plan_season and a.type_id= c.type_id and a.param_id = c.param_id')
            ->join('zl_book_adjust d', "a.year = d.year and a.season = d.season and b.xh = d.xh and c.book_id = d.book_id")
            ->join('zl_book_info f', 'c.book_id = f.id')
            ->join('zl_student_info g', 'b.xh = g.xh')
            ->where(['a.id'=>$extraId, 'b.id'=>$detail_id])
            ->find();

        if($bookInfo){
            $return_data = array(
                'status' => false,
                'msg'    => '删除失败，'.$bookInfo['xm'].'-'.$bookInfo['book_name'].'已调整',
                'data'   => []
            );
            return $return_data;
        }

        $model = new UModel();
        $model->query("call bookExtraDrawDetailDel('".$extraId."', '".$detail_id."');");
         
        $return_data = array(
            'status' => true,
            'msg'    => '删除成功',
            'data'   => []
        );

        return $return_data;
    }

    // 非计划发放：学生明细删除
    public function bookextradrawbookdel()
    { 
        $extraId = input('param.')['extraId'];

        // 判断是否已经退书
        $bookExtraDrawModel = new BookExtraDrawModel();
        $bookInfo = $bookExtraDrawModel->field('f.book_name, g.xm')
            ->alias('a')
            ->join('zl_book_extra_draw_detail b', 'a.id = b.draw_id')
            ->join('zl_student_type_book_rel c', 'a.year = c.plan_year and a.season = c.plan_season and a.type_id= c.type_id and a.param_id = c.param_id')
            ->join('zl_book_return d', "a.year = d.draw_year and a.season = d.draw_season and b.xh = d.xh")
            ->join('zl_book_return_detail e', 'd.id = e.return_id and c.book_id = e.book_id')
            ->join('zl_book_info f', 'c.book_id = f.id')
            ->join('zl_student_info g', 'b.xh = g.xh')
            ->where(['a.id'=>$extraId])
            ->find();

        if($bookInfo){
            $return_data = array(
                'status' => false,
                'msg'    => '删除失败，'.$bookInfo['xm'].'-'.$bookInfo['book_name'].'已退书',
                'data'   => []
            );
            return $return_data;
        }

        // 判断是否已经调整
        $bookExtraDrawModel = new BookExtraDrawModel();
        $bookInfo = $bookExtraDrawModel->field('f.book_name, g.xm')
            ->alias('a')
            ->join('zl_book_extra_draw_detail b', 'a.id = b.draw_id')
            ->join('zl_student_type_book_rel c', 'a.year = c.plan_year and a.season = c.plan_season and a.type_id= c.type_id and a.param_id = c.param_id')
            ->join('zl_book_adjust d', "a.year = d.year and a.season = d.season and b.xh = d.xh and c.book_id = d.book_id")
            ->join('zl_book_info f', 'c.book_id = f.id')
            ->join('zl_student_info g', 'b.xh = g.xh')
            ->where(['a.id'=>$extraId])
            ->find();

        if($bookInfo){
            $return_data = array(
                'status' => false,
                'msg'    => '删除失败，'.$bookInfo['xm'].'-'.$bookInfo['book_name'].'已调整',
                'data'   => []
            );
            return $return_data;
        }

        $model = new UModel();
        $model->query("call bookExtraDrawDel('".$extraId."');");
         
        $return_data = array(
            'status' => true,
            'msg'    => '删除成功',
            'data'   => []
        );

        return $return_data;
    }
    
    // 非计划发放：发放
    public function extradrawsave()
    {
        $this->view->engine->layout(false);
        $bookExtraDrawsModel = new BookExtraDrawsModel();
        if(Request::isPost())
        {
            return $bookExtraDrawsModel->extradrawSave(input('param.'));
        }
        
        //获取年度列表
        $viewGetYearsModel = new ViewGetYearsModel();
        $yearList = $viewGetYearsModel->select();
        $this->assign('yearList', $yearList);

        //获取季度列表
        $viewGetSeasonsModel = new ViewGetSeasonsModel();
        $seasonList = $viewGetSeasonsModel->select();
        $this->assign('seasonList', $seasonList);

        //获取部门列表
        $viewGetDeptsModel = new ViewGetDeptsModel();
        $deptList = $viewGetDeptsModel->select();
        $this->assign('deptList', $deptList);
         
        // 默认值
        $ConfigsModel = new ConfigsModel();
        $year = $ConfigsModel->getYear();
        $season = $ConfigsModel->getSeason();
        $this->assign('year', $year);
        $this->assign('season', $season);
        return $this->fetch('/book_extra_draw/draw');
    }
 
    // 非计划发放：打印状态改变 0->1
    public function bookextraprintstatus()
    {
        $bookExtraDrawsModel = new BookExtraDrawsModel();
        return $bookExtraDrawsModel->bookextraprintstatus(input('param.'));
    }
    
    // 非计划发放：重置打印状态 1->0
    public function bookextraresetprintstatus()
    {
        $bookExtraDrawsModel = new BookExtraDrawsModel();
        return $bookExtraDrawsModel->bookextraresetprintstatus(input('param.'));
    }

    // 非计划发放：非计划发放类型
    public function extratype()
    {       
        if(Request::isAjax())
        {
            $studentTypeModel = new StudentTypeModel();
            return $studentTypeModel->tableData(input('param.'));
        }

        return $this->fetch("/book_extra_draw/type");
    }
    
    /**
     *  非计划发放：非计划发放类型添加
     * @return array|mixed
     */
    public function extratypeadd()
    {
        $this->view->engine->layout(false);
        if(Request::isPost())
        {
            $studentTypeModel = new StudentTypeModel();
            return $studentTypeModel->addData(input('param.'));
        }
        return $this->fetch("/book_extra_draw/typeAdd");
    }

    /**
     *  非计划发放：非计划发放类型修改
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function extratypeedit()
    {
        $this->view->engine->layout(false);
        $studentTypeModel = new StudentTypeModel();
        if(Request::isPost())
        {
            return $studentTypeModel->saveData(input('param.'));
        }
        $data = $studentTypeModel->where('id',input('param.id/d'))->find();
        if (!$data) {
            return error_code(10002);
        }
        return $this->fetch('/book_extra_draw/typeEdit',['data' => $data]);
    }

    /**
     *  非计划发放：非计划发放类型删除
     * User:tony
     * @return array
     */
    public function extratypedel()
    {
        $result = [
            'status' => false,
            'msg' => '删除失败',
            'data' => []
        ];

        $id  = input('post.id', '');

        if ($id == '') {
            return $result;
        }

        $studentTypeParamsModel = new StudentTypeParamsModel();
        $typeParamsInfo = $studentTypeParamsModel->where(['type_id' => $id])->find();
          
        if (!$typeParamsInfo || count($typeParamsInfo) == 0) { 
            $studentTypeModel = new StudentTypeModel();
            $studentTypeModel->where(['id' => $id])->delete();

            $result['status'] = true;
            $result['msg'] = '删除成功';
        } else { 
            $result['msg']    = '当前类型已使用无法删除！';
        }

        return $result;
    }

    // 非计划发放：非计划发放参数
    public function extraparam()
    {         
        if(Request::isAjax())
        {
            $studentTypeParamsModel = new StudentTypeParamsModel();
            return $studentTypeParamsModel->tableData(input('param.'));
        }

        //获取类型
        $studentTypeModel = new StudentTypeModel();
        $typeList = $studentTypeModel->order('sort asc')->select();
        $this->assign('typeList', $typeList);

        return $this->fetch("/book_extra_draw/param");
    }

    /**
     *  非计划发放：非计划发放参数添加
     * @return array|mixed
     */
    public function extratypeparamadd()
    {
        $this->view->engine->layout(false);
        if(Request::isPost())
        {
            $studentTypeParamsModel = new StudentTypeParamsModel();
            return $studentTypeParamsModel->addData(input('param.'));
        }

        //获取年度列表
        $studentTypeModel = new StudentTypeModel();
        $typeList = $studentTypeModel->order('sort asc')->select();
        $this->assign('typeList', $typeList);

        return $this->fetch("/book_extra_draw/paramAdd");
    }

    /**
     *  非计划发放：非计划发放参数修改
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function extratypeparamedit()
    {
        $this->view->engine->layout(false);
        $studentTypeParamsModel = new StudentTypeParamsModel();
        if(Request::isPost())
        {
            return $studentTypeParamsModel->saveData(input('param.'));
        }
        $data = $studentTypeParamsModel->where('id',input('param.id/d'))->find();
        if (!$data) {
            return error_code(10002);
        }
        return $this->fetch('/book_extra_draw/paramEdit',['data' => $data]);
    }

    /**
     *  非计划发放：非计划发放参数删除
     * User:tony
     * @return array
     */
    public function extratypeparamdel()
    {
        $result = [
            'status' => false,
            'msg' => '删除失败',
            'data' => []
        ];

        $id  = input('post.id', '');

        if ($id == '') {
            return $result;
        }

        $studentTypeRelModel = new StudentTypeRelModel();
        $typeRelInfo = $studentTypeRelModel->where(['param_id' => $id])->find();
        
        $studentTypeBookRelModel = new StudentTypeBookRelModel();
        $bookRelInfo = $studentTypeBookRelModel->where(['param_id' => $id])->find();
        
        $bookExtraDrawModel = new BookExtraDrawModel();
        $extraDrawInfo = $bookExtraDrawModel->where(['param_id' => $id])->find();

        if ((!$typeRelInfo || count($typeRelInfo) == 0) &&
            (!$bookRelInfo || count($bookRelInfo) == 0) &&
            (!$extraDrawInfo || count($extraDrawInfo) == 0)) { 
            $studentTypeParamsModel = new StudentTypeParamsModel();
            $studentTypeParamsModel->where(['id' => $id])->delete();

            $result['status'] = true;
            $result['msg'] = '删除成功';
        } else { 
            $result['msg']    = '当前参数已使用无法删除！';
        }

        return $result;
    }

    // 非计划发放：科教中心
    public function subcenter()
    {         

        if(Request::isAjax())
        {
            $viewGetSubCenterModel = new ViewGetSubCenterModel();
            return $viewGetSubCenterModel->tableData(input('param.'));
        }

        //获取部门列表
        $viewGetDeptsModel = new ViewGetDeptsModel();
        $deptList = $viewGetDeptsModel->select();
        $this->assign('deptList', $deptList);

        return $this->fetch("/book_extra_draw/subCenter");
    }

    // 非计划发放：科教中心添加
    public function subcenteradd()
    {    
        if (Request::isPost()) {
            $subCenterModel = new SubCenterModel();
            return $subCenterModel->addData(input('param.'));
        }

        //获取部门列表
        $viewGetDeptsModel = new ViewGetDeptsModel();
        $deptList = $viewGetDeptsModel->select();
        $this->assign('deptList', $deptList);
    
        return $this->fetch('/book_extra_draw/subcenteradd');
    }

    // 非计划发放：科教中心编辑
    public function subcenteredit()
    {         
        $id = input('id', 0);
        $deptName = input('deptName', "");
        $centerName = input('centerName', "");
        $specialtyName = input('specialtyName', "");

        if(Request::isPost())
        {
            $subCenterModel = new SubCenterModel();
            return $subCenterModel->saveData(input('param.'));
        }
        $this->assign('id', $id);
        $this->assign('deptName', $deptName);
        $this->assign('centerName', $centerName);
        $this->assign('specialtyName', $specialtyName);
  
        return $this->fetch("/book_extra_draw/subcenteredit");
    }

    // 非计划发放：科教中心删除
    public function subcenterdel()
    {         
        if (Request::isPost()) {
            $subCenterModel = new SubCenterModel();
            return $subCenterModel->delData(input('param.'));
        }
    }

    
    // 非计划发放：	非计划发放图书关联
    public function BookExtraDrawBookRel()
    {       
        if(Request::isAjax())
        {
            $studentTypeBookRelModel = new StudentTypeBookRelModel();
            return $studentTypeBookRelModel->tableData(input('param.'));
        }

        //获取年度列表
        $viewGetYearsModel = new ViewGetYearsModel();
        $yearList = $viewGetYearsModel->select();
        $this->assign('yearList', $yearList);

        //获取季度列表
        $viewGetSeasonsModel = new ViewGetSeasonsModel();
        $seasonList = $viewGetSeasonsModel->select();
        $this->assign('seasonList', $seasonList);
 
        //获取类型
        $studentTypeModel = new StudentTypeModel();
        $typeList = $studentTypeModel->order('sort asc')->select();
        $this->assign('typeList', $typeList);

        // 默认值
        $ConfigsModel = new ConfigsModel();
        $year = $ConfigsModel->getYear();
        $season = $ConfigsModel->getSeason();
        $this->assign('year', $year);
        $this->assign('season', $season);
        return $this->fetch("/book_extra_draw/bookRel");
    }

    /**
     * 导入非计划发放关联教材信息
     * @return array|mixed
     */
    public function importBookRel()
    {
        if (Request::isPost()) {
            return null;
        }
        return $this->fetch('/book_extra_draw/importBookRel');
    }

    public function BookExtraDrawBookRelAdd()
    {
        $studentTypeBookRelModel = new StudentTypeBookRelModel();

        if (Request::isPost()) {
            $input  = Request::param();
            $result = $studentTypeBookRelModel->addData($input);
            return $result;
        }
 
        $bookInfoModel = new BookInfoModel();
        $bookList = $bookInfoModel->getBookList();
        $this->assign('bookList', $bookList);

        //获取年度列表
        $viewGetYearsModel = new ViewGetYearsModel();
        $yearList = $viewGetYearsModel->select();
        $this->assign('yearList', $yearList);

        //获取季度列表
        $viewGetSeasonsModel = new ViewGetSeasonsModel();
        $seasonList = $viewGetSeasonsModel->select();
        $this->assign('seasonList', $seasonList);

        // 默认值
        $ConfigsModel = new ConfigsModel();
        $year = $ConfigsModel->getYear();
        $season = $ConfigsModel->getSeason();
        $this->assign('year', $year);
        $this->assign('season', $season==1?'春季':'秋季');

        //获取类型
        $studentTypeModel = new StudentTypeModel();
        $typeList = $studentTypeModel->order('sort asc')->select();
        $this->assign('typeList', $typeList);

        return $this->fetch('/book_extra_draw/bookRelAdd');
    }

    public function BookExtraDrawBookRelEdit()
    {
        $studentTypeBookRelModel = new StudentTypeBookRelModel();

        $input  = Request::param();
        if (Request::isPost()) {
            $result = $studentTypeBookRelModel->editData($input);
            return $result;
        }
 
        $relInfo = $studentTypeBookRelModel->where(['id'=>$input['id']])->find();
        $this->assign('relId', $input['id']);
        $this->assign('relInfo', $relInfo);

        $bookInfoModel = new BookInfoModel();
        $bookInfo = $bookInfoModel->where(['id'=>$relInfo['book_id']])->find();
        $this->assign('bookInfo', $bookInfo);
 
        //获取年度列表
        $viewGetYearsModel = new ViewGetYearsModel();
        $yearList = $viewGetYearsModel->select();
        $this->assign('yearList', $yearList);

        //获取季度列表
        $viewGetSeasonsModel = new ViewGetSeasonsModel();
        $seasonList = $viewGetSeasonsModel->select();
        $this->assign('seasonList', $seasonList);

        // 默认值
        $ConfigsModel = new ConfigsModel();
        $year = $ConfigsModel->getYear();
        $season = $ConfigsModel->getSeason();
        $this->assign('year', $year);
        $this->assign('season', $season==1?'春季':'秋季');

        //获取类型
        $studentTypeModel = new StudentTypeModel();
        $typeInfo = $studentTypeModel->where(['id'=>$relInfo['type_id']])->find();
        $this->assign('typeName', $typeInfo['name']);

        //获取参数
        $studentTypeParamsModel = new StudentTypeParamsModel();
        $paramInfo = $studentTypeParamsModel->where(['id'=>$relInfo['param_id']])->find();
        $this->assign('paramName', $paramInfo['name']);
        
        return $this->fetch('/book_extra_draw/bookRelEdit');
    }

    public function BookExtraDrawBookRelDel()
    {
        $id = input('param.')['id'];

        $studentTypeBookRelModel = new StudentTypeBookRelModel();
        // 判断是否已经发过书，发过之后不允许删除
        $relInfo = $studentTypeBookRelModel->where(['id' => $id])->find();
        
        $bookExtraDrawModel = new BookExtraDrawModel(); 
        $drawInfo = $bookExtraDrawModel->where(['year' => $relInfo['plan_year'], 'season' => $relInfo['plan_season'], 'type_id' => $relInfo['type_id'], 'param_id' => $relInfo['param_id']])
            ->find();

        if($drawInfo) {
            $return_data = array(
                'status' => false,
                'msg'    => '该类型参数对应的教材已经发放，不允许删除',
                'data'   => []
            );
    
            return $return_data;    
        }
        
        $studentTypeBookRelModel->where(['id' => $id])->delete();
         
        $return_data = array(
            'status' => true,
            'msg'    => '删除成功',
            'data'   => []
        );

        return $return_data;
    }
}